<?php

namespace App\Repository\CommissionReturn;

use App\Libs\PhpOffice\Excel;
use App\Models\CommissionReturn\CommissionReturnLogsModel as Model;
use App\Models\Order\OrderMoreModel;
use App\Models\Orders\OrdersModel;
use App\Repository\BaseRepository;
use App\Repository\Rebate\RebateLogsRepository;

class CommissionReturnLogsRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new Model();
//    $this->log = new Logger('anchor');
//    $this->log->pushHandler(
//      (new RotatingFileHandler(storage_path('/logs/anchor.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//    );
        parent::__construct();
    }

    //列表
    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        if (isset($params['ordersno']) && !empty($params['ordersno'])) {
            $where['eq']['ordersno'] = trim($params['ordersno']);
        }
        if (isset($params['product_id']) && !empty($params['product_id'])) {
            $where['eq']['product_id'] = trim($params['product_id']);
        }
        if (isset($params['dateRange']) && !empty($params['dateRange'])) {
            $time1 = date('Ym', strtotime($params['dateRange'][0]));
            $time2 = date('Ym', strtotime($params['dateRange'][1]));
            $where['egt']['billing'] = $time1;
            $where['elt']['billing'] = $time2;
        }
        //        先要总数
        $totalRows = 0;
        if ($page == 1) {
            $totalRows = $this->model->searchWhere($where)->count('id');
        }
        $rows = $this->model
            ->searchWhere($where)
            ->page($page, $limit)->orderByDesc('id')->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

    //修改
    public function edit($params = [])
    {
//        $mustField = [
//            'id' => '数据编号不能没有',
//            'money' => '金额不能为空',
//            'rebate_at' => '返费日期不能为空'
//        ];
//        $optionalFields = $this->model->getTableField();
//        $updateData = $this->getRealData($params, array_keys($mustField), $optionalFields, $mustField);
//        if (!empty($updateData) && is_string($updateData)) {
//            //返回错误参数
//            return $this->returnMsg(
//                2,
//                $updateData
//            );
//        }
//        $id = $updateData['id'];
//        $oldRow = $this->model->where(['id' => $id])->select(['type', 'first_at'])->first();
//        $updateData['month'] = $this->computeT($oldRow['first_at'], $updateData['rebate_at']);
//        $updateData['created_by'] = $params['user']['id'];
//        unset($updateData['id']);
//        $res = $this->model->where(['id' => $id])->update($updateData);
//        if (false !== $res) {
//            return $this->returnMsg(200, '修改成功');
//        } else {
//            return $this->returnMsg(20, '修改错误');
//        }
        return $this->returnMsg(20, '修改错误');
    }

//   订单返费信息
    public function importData($moreFileId)
    {
        // 查询出来上传的文件
        $ModelMoreFile = new OrderMoreModel();
        $moreFileData = $ModelMoreFile->where(['id' => $moreFileId, 'is_run' => 0, 'type' => 'commissionReturn'])->first();
        if (!$moreFileData) {
            return $this->returnMsg(1, '未查询到文件' . $moreFileId);
        }
        $shopId = $moreFileData->shop_id;
        $upFile = $moreFileData->upload_rout;
        $upFile = public_path($upFile);
        if (empty($upFile) || !file_exists($upFile)) {
            return $this->returnMsg(100, '文件不存在:' . $upFile);
        }
        if (empty($shopId)) {
            return $this->returnMsg(103, '店铺id 不存在');
        }
        $createdUserId = $moreFileData->created_by;
        $excelClient = new Excel();
        $importData = $excelClient->importFile($upFile, ['billing', 'province', 'city', 'ordersno', 'number', 'product_name', 'account_at', 'account_surname', 'account_name', 'consume_money', 'commission_money', 'tax', 'online'], function ($data) use ($createdUserId) {
            $data['ordersno'] = trim($data['ordersno'] ?? '');
//            $data['province'] = str_replace('省', '', $data['province']);
//            $data['city'] = str_replace(['市', '区', '县'], [''], $data['city']);
            $data['created_by'] = $createdUserId;
            if (!empty($data['account_at'])) {
                if (is_numeric($data['account_at'])) {
                    $data['account_at'] = date('Y-m-d', ($data['account_at'] - 25569) * 3600 * 24);
                } else if (is_string($data['account_at'])) {
                    $data['account_at'] = date('Y-m-d', strtotime(trim($data['account_at'])));
                }
            }
            $data['consume_money'] = abs(trim($data['consume_money']));
            $data['commission_money'] = abs(trim($data['commission_money']));
            $data['tax'] = floatval(trim($data['tax']));
            // 开户月份
            $data['account_month'] = date('Ym', strtotime($data['account_at']));
            //税后佣金金额:开票的税后金额=税前金额 x 税点（1.06）
            if ($data['tax'] > 0) {
                $data['commission_tax_money'] = $data['commission_money'] * $data['tax'];
            } else {
                $data['commission_tax_money'] = $data['commission_money'];
            }
            $data['online'] = intval($data['online']);
            return $data;
        });
        $successNum = 0;
        $failNum = 0;
        $updateNum = 0;
        if (empty($importData['data'])) {
            return $this->returnMsg(2, '文件无数据');
        }
        $ModelOrders = new OrdersModel();
        $RepositoryRebateLogs = new RebateLogsRepository();
        foreach (array_chunk($importData['data'], 100, true) as $key => $rows) {
            // 订单信息
            $ordersNos = [];
            $nowRows = [];
            foreach ($rows as $ni => $nv) {
                $ordersNos[] = $nv['ordersno'];
                $nowRows[$nv['ordersno']] = $nv;
            }
            // 查询订单信息
            $ordersNos = array_unique($ordersNos);
            if (!empty($ordersNos)) {
                $where = [];
                $where['in']['ordersno'] = $ordersNos;
                $md5sumKeys = [];
                $isOnlineData = [];
                foreach ($ModelOrders->searchWhere($where)->select(['id', 'ordersno', 'goods_id', 'goods_name', 'product_id', 'product_name', 'activat_at', 'is_online'])->cursor() as $orderRow) {
                    if (isset($nowRows[$orderRow->ordersno])) {
//                        $nowRows[$orderRow->ordersno]['orders_id'] = $orderRow->id;
                        $nowRows[$orderRow->ordersno]['product_id'] = $orderRow->product_id;
                        $nowRows[$orderRow->ordersno]['product_name'] = $orderRow->product_name;
                        $nowRows[$orderRow->ordersno]['goods_id'] = $orderRow->goods_id;
                        $nowRows[$orderRow->ordersno]['goods_name'] = $orderRow->goods_name;
                        $nowRows[$orderRow->ordersno]['activat_at'] = $orderRow->activat_at;
                        $billingDate = substr_replace($nowRows[$orderRow->ordersno]['billing'], '-', 4, 0) . '-01 00:00:00';
                        $nowRows[$orderRow->ordersno]['billing_at'] = date('Y-m-d', strtotime($billingDate));
                        $nowRows[$orderRow->ordersno]['online_t'] = 0;
                        $nowRows[$orderRow->ordersno]['activat_month'] = 0;
                        // 计算在网T
                        if (!empty($orderRow->activat_at)) {
                            $nowRows[$orderRow->ordersno]['activat_month'] = date("Ym", strtotime($orderRow->activat_at));
                            $nowRows[$orderRow->ordersno]['online_t'] = $RepositoryRebateLogs->computeT($orderRow->activat_at, $billingDate);
                        }
                        // md5sum
//                        $md5sum = md5($orderRow->ordersno . $nowRows[$orderRow->ordersno]['billing']);
//                        $md5sumKeys[] = $md5sum;
//                        $nowRows[$orderRow->ordersno]['md5sum'] = $md5sum;
                        //记录一下在网情况
                        $isOnlineData[$orderRow->ordersno] = $orderRow->is_online;
                    }
                }
//                if (!empty($md5sumKeys)) {
                $newAddRows = [];
//                $willUpdateData = [];
//                    $where = [];
//                    $where['in']['md5sum'] = $md5sumKeys;
//                    foreach ($this->model->searchWhere($where)->select(['id', 'ordersno'])->cursor() as $oldRow) {
//                        $willUpdateData[$oldRow->ordersno] = $oldRow->id;
//                    }
                foreach ($nowRows as $nk => $nv) {
                    if (empty($nv['ordersno'])) {
                        $failNum += 1;
                    } else {
                        $successNum += 1;
//                        if (isset($willUpdateData[$nv['ordersno']])) {
//                            $updateNum += 1;
//                            $this->model->where(['id' => $willUpdateData[$nv['ordersno']]])->update($nv);
//                        } else {
//                            $newAddRows[] = $nv;
//                        }
                        $newAddRows[] = $nv;
                        // 更新订单表的在网情况
                        if ($isOnlineData[$nv['ordersno']] != $nv['online']) {
                            $ModelOrders->where(['ordersno' => $nv['ordersno']])->update(['is_online' => $nv['online']]);
                        }
                    }
                }
                if (!empty($newAddRows)) {
                    $this->model->insert($newAddRows);
                }
                //}
            }
        }
        $ModelMoreFile->where(['id' => $moreFileData['id']])->update(['is_run' => 1, 'fail_num' => $failNum, 'success_num' => $successNum + $updateNum]);
        return $this->returnMsg(200, '文件处理完成', ['updateNum' => $updateNum]);
    }
}
